<template>
  <div class="chat chat-start mt-2" :class="{'ml-3 border-l-2 border-gray-400 pl-4': commentItem && commentItem?.parentId !== 0 }">
    <!-- 头像 -->
    <div class="chat-image avatar self-start">
      <div class="w-9 rounded-full">
        <img :src="commentItem?.avatar" alt="avatar"/>
      </div>
    </div>
    <!-- 用户信息 -->
    <div class="chat-header flex w-full justify-between items-center">
      <div class="user-info flex-grow-1">
        <div>
          <span class="opacity-50 mr-1">{{ commentItem?.nickName }}</span>
          <Icon v-if="authorId === commentItem?.userId" color="#00dc82" size="20" name="solar:verified-check-bold"/>
          <span class="opacity-50 ml-2" v-if="commentItem?.answerId">回复 {{ commentItem.answerNickName }}</span>
        </div>
        <div class="text-xs opacity-50">
          <time class="mr-2">{{ getLastTimeStr(commentItem.createTime, true) }}</time>
          <span>IP属地：{{ commentItem.ipSource }} </span>
        </div>
      </div>
      <div class="flex">
        <!-- 删除按钮 -->
        <div class="cursor-pointer opacity-50" v-if="commentItem?.userId === userInfo?.userId">
          <button class="btn btn-sm btn-ghost" @click="onDeleteComment(commentItem?.commentId as string)">
            <Icon size="14" name="ant-design:delete-outlined"/>
          </button>
        </div>
        <!-- 回复按钮 -->
        <div class="cursor-pointer opacity-50" @click="replyBoxVisible = !replyBoxVisible">
          <button class="btn btn-sm btn-ghost">
            <Icon v-if="replyBoxVisible" size="14" name="tabler:message-circle-off"/>
            <Icon v-else size="14" name="ant-design:message-outlined"/>
          </button>
        </div>
      </div>
    </div>
    <div class="comment-content" style="word-break: break-word;">{{ commentItem.commentContent }}</div>
  </div>
  <!-- 回复框 -->
  <div v-if="replyBoxVisible" class="ml-10 flex items-end">
    <textarea class="textarea textarea-warning w-full bg-opacity-30 backdrop-filter backdrop-blur-lg"
              :placeholder="`@ ${commentItem?.nickName}`" v-model="commentInfo.commentContent"></textarea>
    <button class="btn btn-outline w-20 ml-3 h-full" @click="onReply(commentItem)">回复</button>
  </div>
  <!-- 递归渲染子评论 -->
  <div v-if="commentItem?.children && commentItem?.children.length > 0">
    <AnnCommentItem v-for="child in commentItem?.children" :key="child.commentId"
                    :commentItem="child" :author-id="authorId" @refresh="onRefresh"/>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive} from 'vue';
import {getUserInfoFromCookie} from '~/utils/cookie';
import type {BlogCommentWebBo, BlogCommentWebVO} from '~/api/comment/types';
import type {BlogUserWebVO} from '~/api/user/types';
import {removeComment} from '~/api/comment';
import {comment} from '~/api/article';
import {getLastTimeStr} from '~/utils/timeUtils';
import {showMessage, showModal} from '~/utils/toast';
import type {ModalOptions} from '~/utils/toast';

const emits = defineEmits(['refresh']);
const replyBoxVisible = ref(false);

defineProps({
  commentItem: {
    type: Object as () => BlogCommentWebVO,
    required: true,
  },
  authorId: {
    type: [String, Number] as unknown as () => string | number,
    required: true,
  },
});

// 登录用户信息
const userInfo = ref<BlogUserWebVO>({
  userId: '',
  nickName: '',
  avatar: '',
  sex: '',
});
const commentInfo = reactive<BlogCommentWebBo>({
  topicId: "",
  commentContent: "",
  parentId: "",
  answerId: "",
});

// 获取用户信息
const getInfo = async () => {
  userInfo.value = await getUserInfoFromCookie();
};
getInfo();

// 回复评论
const onReply = async (commentItem: BlogCommentWebVO) => {
  commentInfo.topicId = commentItem.topicId;
  commentInfo.answerId = commentItem.userId;
  commentInfo.parentId = commentItem.parentId === 0 ? commentItem.commentId : commentItem.parentId;
  const {data: res} = await useAsyncData("comment", () =>
      comment(commentInfo));
  if (res.value?.code == 200) {
    commentInfo.commentContent = '';
    replyBoxVisible.value = false;
    emits('refresh');
    showMessage('评论成功', 'success');
  }
};
// 踩坑...嵌套子组件时，并且还让父组件监听了，要这样
// 刷新
const onRefresh = (): void => {
  emits('refresh');
};

// 删除按钮
const onDeleteComment = (commentId: string | number): void => {
  const options: ModalOptions = {
    type: 'danger',
    title: '提示',
    body: '删除评论后，评论下所有回复都会被删除<p>是否继续?</p>',
    primary: {
      label: '是',
      theme: 'red',
      action: () => {
        delComment(commentId);
      },
    },
    secondary: {
      label: '否',
      theme: 'white',
      action: () => {
      },
    },
  };
  showModal(options);
};

// 删除评论
const delComment = async (commentId: string | number) => {
  const {data: res} = await useAsyncData("removeComment", () =>
      removeComment(commentId));
  if (res.value?.code == 200) {
    showMessage('删除成功');
    emits('refresh');
  }
};
</script>
